/**
 * axios二次封装
 */
import axios from 'axios'
import config from '../config/index.js'
import { ElMessage } from 'element-plus'
//创建axios实例，添加全局配置
const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000
})
//请求拦截
service.interceptors.request.use((req) => {
    //如果是开发环境且开启了mock则使用mockapi
    const headers = req.headers;
    if (!headers.Authorization) headers.Authorization = "xxxxxx"
    return req
})
//响应拦截
service.interceptors.response.use((res) => {
    const { code, data, msg } = res.data
    if (code === 200) {
        return data
    } else if (code === 4001) {
        ElMessage.error(msg);
        setTimeout(() => {
            routerKey.push('/login')
        }, 15000);
        return Promise.reject(msg)
    } else {
        return Promise.reject(msg || '网络请求异常，请稍后重试！')
    }
}, (error) => {
    return Promise.reject(error)
})
export default service

//请求工具函数
export const request = (options) => {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    if (config.env === 'production') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }
    return service(options)
}